package pers.whj.sort;

public abstract class Sort<T> {
    public static final int MAX_SIZE = 50000000;

    protected T[] mData;
    protected Compare<T> mCompare;

    public Sort(T[] data) throws SortException {
        this(data, null);
    }

    public Sort(T[] data, Compare<T> compare) throws SortException {
        setData(data);
        setCompare(compare);
    }

    public void setData(T[] data) throws SortException {
        if (data == null) {
            throw new SortException(SortException.EMPTY_DATA);
        } else if (data.length > MAX_SIZE) {
            throw new SortException(SortException.LARGE_DATA);
        } else {
            this.mData = data;
        }
    }

    public void setCompare(Compare<T> compare) {
        if (compare == null) {
            compare = (a, b) -> false;
        }
        this.mCompare = compare;
    }

    public void sort() throws SortException {
        sort(0, mData.length - 1);
    }

    public abstract void sort(int left, int right) throws SortException;

    protected static <E> void check(E[] data, Compare<E> compare, int left, int right) throws SortException {
        if (data == null) {
            throw new SortException(SortException.EMPTY_DATA);
        } else if (data.length > MAX_SIZE) {
            throw new SortException(SortException.LARGE_DATA);
        } else if (left > right || left < 0 || right >= data.length) {
            throw new SortException(SortException.CROSS_BORDER);
        }
        //check if compare is null
        if (compare == null) {
            compare = (a, b) -> false;
        }
    }
}